package cz.muni.fi.pv168.ContactManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Vlado
 * Date: 4.3.2012
 * Time: 17:38
 * To change this template use File | Settings | File Templates.
 */
public class ContactManagerImpl implements ContactManager {
    private DataSource dataSource;

    private final static Logger log = LoggerFactory.getLogger(ContactManagerImpl.class);

    public void setDataSource(DataSource ds)
    {
        this.dataSource = ds;
    }

    @Override
    public Contact createContact(Contact contact) {
        if(dataSource == null) throw new IllegalStateException("Data source is not set!");
        if(contact == null) throw new NullPointerException("contact");
        if(contact.getId() != null) throw new IllegalEntityException("Id is not null!");
        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = dataSource.getConnection();
            st = conn.prepareStatement(
                    "INSERT INTO CONTACT (CONTACTTYPE,CONTACTVALUE,PERSONID) VALUES (?,?,NULL)",
                    Statement.RETURN_GENERATED_KEYS);
            st.setString(1, contact.getType());
            st.setString(2, contact.getValue());

            int count = st.executeUpdate();
            if (count != 1)
            {
                String msg = "Error when inserting contact into db";
                log.error(msg);
                throw new ServiceFailureException(msg);
            }
            ResultSet key = st.getGeneratedKeys();
            Long id = null;
            key.next();
            id = key.getLong(1);
            if(id == null) return null;
            contact.setId(id);
        } catch (SQLException ex) {
            String msg = "Error when inserting contact into db";
            log.error(msg,ex);
            throw new ServiceFailureException(msg, ex);
        } finally {
            try {if(st != null) {st.close();}}
            catch (SQLException ex) {log.error("Error when closing statement", ex);}
            try {if(conn != null) {conn.close();}}
            catch (SQLException ex) {log.error("Error when closing connection", ex);}
        }
        return contact;
    }

    @Override
    public void deleteContact(Contact contact) {
        if(dataSource == null) throw new IllegalStateException("Data source is not set!");
        if(contact == null) throw new NullPointerException("contact");
        if(contact.getId() == null) throw new IllegalEntityException("Id is null!");
        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = dataSource.getConnection();
            st = conn.prepareStatement(
                    "DELETE FROM CONTACT WHERE ID = ?");
            st.setLong(1, contact.getId());
            int count = st.executeUpdate();
            if (count > 1)
            {
                String msg = "More than one contact with same ID";
                log.error(msg);
                throw new ServiceFailureException(msg);
            }
            if (count == 0){
                String msg = "No contact with the ID";
                log.error(msg);
                throw new IllegalEntityException(msg);
            }
        } catch (SQLException ex) {
            String msg = "Error when deleting contact from db";
            log.error(msg,ex);
            throw new ServiceFailureException(msg, ex);
        } finally {
            try {if(st != null) {st.close();}}
            catch (SQLException ex) {log.error("Error when closing statement", ex);}
            try {if(conn != null) {conn.close();}}
            catch (SQLException ex) {log.error("Error when closing connection", ex);}
        }
    }

    @Override
    public void updateContact(Contact contact) {
        if(dataSource == null) throw new IllegalStateException("Data source is not set!");
        if(contact == null) throw new NullPointerException("contact");
        if(contact.getId() == null) throw new IllegalEntityException("Id is null!");
        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = dataSource.getConnection();
            st = conn.prepareStatement(
                    "UPDATE CONTACT SET CONTACTTYPE = ?, CONTACTVALUE = ? WHERE ID = ?");
            st.setString(1, contact.getType());
            st.setString(2, contact.getValue());
            st.setLong(3, contact.getId());

            int count = st.executeUpdate();
            if (count != 1)
            {
                String msg = "Error when updating contact in db";
                log.error(msg);
                throw new ServiceFailureException(msg);
            }
        } catch (SQLException ex) {
            String msg = "Error when updating contact in db";
            log.error(msg,ex);
            throw new ServiceFailureException(msg, ex);
        } finally {
            try {if(st != null) {st.close();}}
            catch (SQLException ex) {log.error("Error when closing statement", ex);}
            try {if(conn != null) {conn.close();}}
            catch (SQLException ex) {log.error("Error when closing connection", ex);}
        }
    }

    @Override
    public Contact findContactById(Long id) {
        if(dataSource == null) throw new IllegalStateException("Data source is not set!");
        if(id == null) throw new NullPointerException("id");
        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = dataSource.getConnection();
            st = conn.prepareStatement(
                    "SELECT ID, CONTACTTYPE, CONTACTVALUE FROM CONTACT WHERE ID = ?");
            st.setLong(1, id);
            ResultSet rs = st.executeQuery();

            if (rs.next())
            {
                Contact result = rowToContact(rs);
                if (rs.next())
                {
                    String msg = "More contacts with same ID";
                    log.error(msg);
                    throw new ServiceFailureException(msg);
                }
                return result;
            }
            else
            {
                return null;
            }

        } catch (SQLException ex) {
            String msg = "Error when getting person from db";
            log.error(msg,ex);
            throw new ServiceFailureException(msg, ex);
        } finally {
            try {if(st != null) {st.close();}}
            catch (SQLException ex) {log.error("Error when closing statement", ex);}
            try {if(conn != null) {conn.close();}}
            catch (SQLException ex) {log.error("Error when closing connection", ex);}
        }
    }

    @Override
    public List<Contact> findContactByValue(String value) {
        if(dataSource == null) throw new IllegalStateException("Data source is not set!");
        if(value == null) throw new NullPointerException("value");
        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = dataSource.getConnection();
            st = conn.prepareStatement(
                    "SELECT ID, CONTACTTYPE, CONTACTVALUE FROM CONTACT WHERE CONTACTVALUE = ?");
            st.setString(1,value);
            ResultSet rs = st.executeQuery();
            List<Contact> result = new ArrayList<Contact>();
            while (rs.next()) {
                result.add(rowToContact(rs));
            }
            return result;
        } catch (SQLException ex) {
            String msg = "Error when getting contacts from db";
            log.error(msg,ex);
            throw new ServiceFailureException(msg, ex);
        } finally {
            try {if(st != null) {st.close();}}
            catch (SQLException ex) {log.error("Error when closing statement", ex);}
            try {if(conn != null) {conn.close();}}
            catch (SQLException ex) {log.error("Error when closing connection", ex);}
        }
    }

    private static Contact rowToContact(ResultSet rs) throws SQLException {
        Contact result = new Contact();
        result.setId(rs.getLong("ID"));
        result.setType(rs.getString("CONTACTTYPE"));
        result.setValue(rs.getString("CONTACTVALUE"));
        return result;
    }
}
